package com.yanqu.road.server.cmd.banquet.cross;

import com.yanqu.road.entity.banquet.UserCrossBanquetData;
import com.yanqu.road.pb.banquet.BanquetProto;
import com.yanqu.road.pb.banquet.CrossBanquetProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.banquet.BanquetMgr;
import com.yanqu.road.server.manger.banquet.CrossBanquetAutoOpenMgr;
import com.yanqu.road.server.manger.banquet.CrossBanquetMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.string.StringUtils;

@Cmd(code = Protocol.S_BANQUET_CROSS_OPEN_RESP, desc = "预开启宴会返回")
public class CrossBanquetOpenRespCmd extends AbstractCommand {


	private int res;//返回的结果
	private String banquetId;
	private long openTime;
	private long overTime;
	private boolean autoOpen;
	private int giftId;
	String reward;

	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		CrossBanquetProto.OpenCrossBanquetResp reqMsg = CrossBanquetProto.OpenCrossBanquetResp.parseFrom(packet.getBytes());
		res = reqMsg.getRet();
		banquetId = reqMsg.getBanquetId();
		openTime = reqMsg.getOpenTime();
		overTime = reqMsg.getOverTime();
		if (reqMsg.hasAutoOpen()) {
			autoOpen = reqMsg.getAutoOpen();
		}
		giftId = reqMsg.getGiftId();
		return true;
	}

	@Override
	public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
		if(res != 0){
			ret = res;
			if(autoOpen){
				if(player == null){
					player = GamePlayerMgr.getPlayer(packet.getPlayerId());
				}
				UserCrossBanquetData userCrossBanquetData = CrossBanquetMgr.getBanquet(banquetId);
				if(userCrossBanquetData != null && player != null) {
					CrossBanquetAutoOpenMgr.preUpdateAutoOpenFail(player, userCrossBanquetData.getType());
				}
			}
		}else {
			ret = CrossBanquetMgr.successCrossBanquet(player, banquetId, openTime, overTime, autoOpen);
			if (0 == ret) {
				if (giftId > 0) {
					reward = CrossBanquetMgr.joinCrossBanquet(player, banquetId, giftId, 1);
				}
				BanquetMgr.addBanquetConductTimes(player);
			}
		}
	}

	@Override
	public void sendData(GamePlayer player) {
		BanquetProto.OpenBanquetResp.Builder respMsg = BanquetProto.OpenBanquetResp.newBuilder();
		respMsg.setRet(ret);
		if (!StringUtils.isNullOrEmpty(reward)) {
			respMsg.setReward(reward);
		}
		player.sendPacket(Protocol.U_BANQUET_CROSS_OPEN, respMsg);
	}
}
